package com.turing.draw.task;

import com.turing.common.entity.Context;
import com.turing.common.response.ResponseVO;
import com.turing.draw.client.reviewer.ReviewTaskInnerService;
import com.turing.draw.model.domain.DrawTask;
import com.turing.draw.model.domain.FileTask;
import com.turing.draw.client.reviewer.ReviewerOpClient;
import com.turing.draw.enums.FileStatusEnum;
import com.turing.draw.enums.TaskStatusEnum;
import com.turing.draw.service.FileTaskService;
import com.turing.draw.service.DrawTaskService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Component
public class PostProcessorTask {

    private Log logger = LogFactory.getLog(PostProcessorTask.class);

    @Autowired
    private DrawTaskService drawTaskService;

    @Autowired
    private FileTaskService fileTaskService;

    @Autowired
    private ReviewerOpClient reviewerOpClient;

    @Autowired
    private ReviewTaskInnerService reviewTaskInnerService;

    @Async("postProcessorTaskExecutor")
    @Transactional(propagation = Propagation.REQUIRED)
    public void doPostProcessor(String parentTaskSn, String taskSn, String templateSn) {

        DrawTask drawTask = drawTaskService.lambdaQuery().eq(DrawTask::getTaskSn, parentTaskSn)
                .select(DrawTask::getCreatedBy)
                .one();

        reviewerOpClient.populateEmptyElements(parentTaskSn,templateSn);
        logger.info("all file tasks finished,start doing post processor,taskSn is:"+parentTaskSn);
        // run scripts
        boolean run = false;
        if (drawTask != null) {
            run = drawTask.getCreatedBy().equals(34);
        }
        if (!run) {
            logger.info("start doing scripts task,taskSn is:"+parentTaskSn);

            ResponseVO<String> scriptsRes = reviewTaskInnerService.runScriptsTask(parentTaskSn);
            logger.info("run scripts task,result is:"+scriptsRes.getCode().equals("200"));

        }

        // update task record taskStatus
        boolean taskRecordUpdate = drawTaskService.lambdaUpdate().eq(DrawTask::getTaskSn, taskSn)
                .set(DrawTask::getTaskStatus, TaskStatusEnum.DRAWFINISHED.getCode())
                //.set(DrawTask::getUpdatedBy, Context.getTokenContext().getUserId())
                .update();
        logger.info("finish do post processor,update task record,result is:"+taskRecordUpdate);

    }

}
